#import "XMAudioPlayer.h"
#import <SDWebImage/SDWeakProxy.h>
@interface XMAudioPlayer () <AVAudioPlayerDelegate>
@property (nonatomic, strong) AVAudioPlayer *player;
@property (nonatomic, weak) CADisplayLink *displayLink;
@end


@implementation XMAudioPlayer
+ (XMAudioPlayer *)sharedInstance {
    static XMAudioPlayer *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}
- (void)startPlayVoiceData:(NSData *)data time:(float)time {
    [self stopPlay];
    NSError *playerError;
    self.player = [[AVAudioPlayer alloc] initWithData:data error:&playerError];
    self.player.delegate = self;
    self.player.currentTime = self.player.duration * time;
    
    if (!playerError) {
        self.player.numberOfLoops = 0;
        self.player.volume = 1.0;
        [self.player prepareToPlay];
        [self.player play];
    }
    
    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:[SDWeakProxy proxyWithTarget:self] selector:@selector(update)];
    displayLink.paused = NO;
    [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    self.displayLink = displayLink;
}
- (void)pausePlay {
    if ([self.player isPlaying]) {
        [self.player pause];
        self.displayLink.paused = YES;
    }
}
- (void)stopPlay {
    [self invalidateDisplayLink];
    if (self.player) {
        [self.player stop];
        self.player = nil;
    }
}
- (void)invalidateDisplayLink {
    if (self.displayLink) {
        self.displayLink.paused = YES;
        [self.displayLink invalidate];
        self.displayLink = nil;
    }
}
- (BOOL)isPlaying {
    return self.player.isPlaying;
}
- (float)curTime {
    return self.player.currentTime;
}
- (float)duration {
    return self.player.duration;
}
- (void)update {
    XMWeakSelf(self);
    if ([self.delegate respondsToSelector:@selector(playerPlaying:duration:)]) {
        XMStrongSelf(self)
            [self.delegate playerPlaying:self.player.currentTime
                                duration:self.player.duration];
    }
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    [[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
    if ([self.delegate respondsToSelector:@selector(playerDidFinishPlaying:flag:)]) {
        [self.delegate playerDidFinishPlaying:player flag:flag];
    }
}
@end
